package service

import (
	"bluebell-backend/common"
	"bluebell-backend/dao/mysql"
	"bluebell-backend/dao/redis"
	"bluebell-backend/model/po"
	"fmt"
	"sync"
)

func AddPost(post *po.Post) (int, error) {
	// 添加到mysql中
	pId, err := idGen.NextId()
	if err != nil {
		fmt.Println("错误")
		return common.ERROR, err
	}
	post.PId = pId
	var wg sync.WaitGroup
	errChan := make(chan error, 2)
	wg.Add(2)
	go func() {
		defer wg.Done()
		_, err := mysql.NewPostDaoInstance().InsertPost(post)
		errChan <- err
	}()

	// 添加到redis中
	go func() {
		defer wg.Done()
		err := redis.InsertPost(post)
		errChan <- err

	}()
	wg.Wait()
	select {
	case err := <-errChan:
		if err != nil {
			return common.ERROR, err
		}
	default:

	}
	return common.SUCCESS, nil
}

func UpdatePost(post *po.Post) (int, error) {
	return mysql.NewPostDaoInstance().UpdatePost(post)
}

func GetPostInfo(id int64) (*po.Post, error) {
	return mysql.NewPostDaoInstance().GetOnePostById(id)
}
